<?php

namespace app\job;

use app\common\GptService;
use app\common\MailService;
use app\common\TencentIm;
use app\model\TalentGoodsOrders;
use Carbon\Carbon;
use think\facade\Log;
use think\queue\Job;

class Task
{

    public function fire(Job $job, $data)
    {
        $rt = $this->doJob($data);
        if($rt){
            $job->delete();
            return true;
        }

        // 重试三次失败 todo...
        if($job->attempts() >= 3){
	        $job->release(60*60*24);
	        MailService::SendMail('199464387@qq.com','队列异常','队列处理失败,请排查');
        }else{
	        //执行失败10S后重试
	        $job->release(10);
        }
    }

    public function doJob($data)
    {
        if (array_key_exists('action',$data)){
            //超时系统自动操作
            switch ($data['action']){
                case 'QuestionBot':
                    $res=event('QuestionBot', $data['data']['id']); //增加机器人第一条回复
                    if (!$res[0]){
                        return false;
                    }
                    break;
                case 'AiDoc':
                    $res=event('TalentAiDoc', $data['data']['id']);
                    if (!$res[0]){
                        return false;
                    }
                    break;
	            case 'SendMsg':
					$users_id = $data['data']['users_id'];
					$content = $data['data']['content'];
		            $res=GptService::ask($content);
		            $res=json_decode($res);
		            if ($res->code!=200){
			            return  false;
		            }
		            //回答
		            $answer=$res->data->choices[0]->message->content;
		            $TencentIm = TencentIm::getInstance();
		            $ret=json_decode($TencentIm->send_msg('3',$users_id,[['MsgType'=>'TIMTextElem','MsgContent'=>['Text'=>$answer]]]));
		            if ($ret->ErrorCode!=0){
			            return false;
		            }
					break;
	            case 'TalentGoodsServiceOver':
					$id = $data['data']['id'];
					$order  = TalentGoodsOrders::find($id);
					if ($order->pay_status==1&&$order->expiretime<=time()){
						$order->pay_status=2;
						$order->save();
					}
					break;
	            case 'TalentGoodSendMail':
		            $id = $data['data']['id'];
		            $order  = TalentGoodsOrders::find($id);
					//专业团队订单提醒
		            $ret = MailService::SendMail('199464387@qq.com','订单提醒','您有一条新的专业团队订单，请及时处理');
					if (!$ret){
						return false;
					}
					break;
            }
        }
        return true;
    }



}